package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SupplierServiceImpl
 * @Author 波
 * @Date 2024/9/24 10:27
 */
@Service
public class SupplierServiceImpl implements SupplierService {
    @Autowired
    private SupplierDao supplierDao;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String supplierName) {
        page = page == 0 ? 1 : page;
        int offSet = (page - 1) * rows;
        HashMap<String, Object> map = new HashMap<>();
        try {
            List<Supplier> supplierList = supplierDao.list(offSet, rows, supplierName);
            int count = supplierDao.getCount(supplierName);
            map.put("rows", supplierList);
            map.put("total", count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public void save(Supplier supplier) {
        Integer supplierId = supplier.getSupplierId();
        String supplierName = supplier.getSupplierName();
        String contacts = supplier.getContacts();
        String phoneNumber = supplier.getPhoneNumber();
        String address = supplier.getAddress();
        String remarks = supplier.getRemarks();

        if (supplierId == null) {
            int saveResult = supplierDao.save(supplierName, contacts, phoneNumber, address, remarks);
            if (saveResult == 0) {
                throw new RuntimeException("添加供应商失败");
            }
        } else {
            int updateResult = supplierDao.update(supplierId, supplierName, contacts, phoneNumber, address, remarks);
            if (updateResult == 0) {
                throw new RuntimeException("修改供应商失败");
            }
        }
    }

    @Override
    public void delete(String ids) {
        String[] idsArray = ids.split(",");
        for (String id : idsArray) {
            int deleteResult = supplierDao.delete(Integer.parseInt(id));
            if (deleteResult == 0) {
                throw new RuntimeException("删除供应商失败");
            }
        }
    }
}
